
//#include "head.h"
//#include <stdio.h>
#include <unistd.h>
#include <signal.h>

#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/RedisMessage.h>
using std::cout;
using std::endl;
using std::string;
using std::vector;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf(">> sig num %d is comming\n", num);
    //调用一次done方法，计数器的值减1
    waitGroup.done();
}

//4. 设计回调函数
void redisCallback(WFRedisTask * redistask)
{
    printf("redisCallback is running\n");
    // 1. 错误的检测
    int state = redistask->get_state();
    int error = redistask->get_error();
    switch(state) {
    case WFT_STATE_SYS_ERROR:
        printf("system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        printf("dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        break;
    }
    if(state != WFT_STATE_SUCCESS) {
        printf("error occurs!\n");
        return;
    }
    printf("task is ok!\n");
    //2. 对Redis请求报文进行遍历
    auto req = redistask->get_req();
    string command;
    vector<string> params;
    req->get_command(command);
    req->get_params(params);
    cout << "> RedisRequest: " << command << " ";
    for(auto & elem : params) {
        cout << elem << " ";
    }
    cout << endl << endl;

    //3. 对Redis响应报文进行遍历
    auto resp = redistask->get_resp();
    protocol::RedisValue result;
    resp->get_result(result);

    if(result.is_string()) {
        cout << "RedisValue is string" << endl;
        cout << result.string_value() << endl;
    } else if(result.is_int()) {
        cout << "RedisValue is integer" << endl;
        cout << result.int_value() << endl;
    } else if(result.is_array()) {
        cout << "RedisValue is array" << endl;
        for(size_t i = 0; i < result.arr_size(); ++i) {
            cout << i+1 << ") " 
                 << result.arr_at(i).string_value() 
                 << endl;
        }
    }
}

void test0()
{
    signal(SIGINT, sighandler);
    string url = "redis://localhost:6379";
    //1. 创建任务1
    auto redisTask = WFTaskFactory::create_redis_task(url, 1, redisCallback);
    string command = "SET";
    vector<string> params {"x", "123"};
    redisTask->get_req()->set_request(command, params);
    //2. 创建任务2
    auto redisTask2 = WFTaskFactory::create_redis_task(url, 1, redisCallback);
    command = "GET";
    params = {"x"};
    redisTask2->get_req()->set_request(command, params);
    //3. 创建序列, 但并不启动任务的执行
    auto series = Workflow::create_series_work(redisTask, nullptr);
    //4. 添加第二个任务
    series->push_back(redisTask);
    //5. 序列交由框架调度资源来运行任务
    series->start();

    //当调用wait方法会阻塞当前线程
    waitGroup.wait();

    cout << "test0 exit" << endl;
}


int main()
{
    test0();
    return 0;
}

